package utils

import (
	"openapi.itspire.cn/common/global"
	"bytes"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

type Response struct {
	Code 	  int		  `json:"code"`
	Msg  	  string      `json:"msg"`
	Data 	  interface{} `json:"data"`
	RequestID int64 	  `json:"requestID"`
}

func JsonParams(c *gin.Context) map[string]interface{} {
	b, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		panic(err)
	}

	// 将取出来的body内容重新插入body，否则ShouldBindJSON无法绑定参数
	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(b))
	return JsonDecode(string(b))
}

func Success(c *gin.Context, data interface{}) {
	if data == nil {
		data = make([]string, 0)
	}
	response := Response{ Code: 0, Msg: "success", Data: data, RequestID: global.RequestID }
	SetResponseData(c, response)
	c.JSON(http.StatusOK, response)
}

func Error(c *gin.Context, err string, code int, status int, level string) {
	response := Response{ Code: code, Msg: err, Data: make([]string, 0), RequestID: global.RequestID }
	SetResponseData(c, response)
	SetLevel(c, level)
	c.JSON(status, response)
}

func SetResponseData(c *gin.Context, response interface{}) {
	c.Set("responseData", response)
}

func GetResponseData(c *gin.Context) interface{} {
	response, _ := c.Get("responseData")
	return response
}

func SetLevel(c *gin.Context, level interface{}) {
	c.Set("level", level)
}

func GetLevel(c *gin.Context) interface{} {
	level, _ := c.Get("level")
	return level
}

func SetUserInfo(c *gin.Context, data interface{}) {
	c.Set("userInfo", data)
}

func GetUserInfo(c *gin.Context) map[string]interface{} {
	data, _ := c.Get("userInfo")
	maps := make(map[string]interface{})
	maps = StructToMap(data, "json")
	return maps
}

